<?php

include_once "db.php";
include_once "user.php";
include_once "chapter.php";
include_once "region.php";

/*
Factory used to create objects of the User, Chapter, and Region classes.
Removes need of user to know database design.
Allows for multiple constructors (PHP does not allow method overloading).
*/
class Factory
{
    public function __construct()
    {
    }

    //Gets a user by the user's email
    public function getUserByEmail($email, $password, $hashed = false)
    {
        global $mysqli;
        $queryemail = mysqli_real_escape_string($mysqli, $email);
        if ($hashed)
        {
            $querypassword = mysqli_real_escape_string($mysqli, $password);
        } else
        {
            $querypassword = mysqli_real_escape_string($mysqli, sha1($password));
        }
        $query = "SELECT * FROM Users WHERE Email = '" . $queryemail .
            "' AND Password = '" . $querypassword . "'";
        $data = $mysqli->query($query);
        if ($data->num_rows != 0)
        {
            $row = $data->fetch_array(MYSQLI_ASSOC);
            $chapter = $this->getChapterById($row['ChapterID']);
            if (!empty($chapter))
            {
                $myuser = new User($email, $password, $chapter, $hashed);
                if ($myuser->userFound())
                {
                    return $myuser;
                }
                return null;
            }
            return null;
        }
        return null;
    }

    //Gets a chapter by a chapter id
    public function getChapterById($id)
    {
        global $mysqli;
        $chapter = new Chapter($id);
        if ($chapter->chapterFound())
        {
            return $chapter;
        }
        return null;
    }

    //Gets a chapter by a user's id
    public function getChapterByUserId($id)
    {
        global $mysqli;
        $queryid = mysqli_real_escape_string($mysqli, $id);
        $query = "SELECT * FROM Users u, Chapters c WHERE u.UserID = '" . $queryid .
            "' AND u.ChapterID = c.ChapterID";
        if ($data->num_rows != 0)
        {
            $row = $data->fetch_array(MYSQLI_ASSOC);
            $chapterid = $row['ChapterID'];
            return $this->getChapterById($chapterid);
        }
    }

    //Gets list of all regions in database
    public function getRegionList()
    {
        global $mysqli;
        $query = "SELECT * FROM Regions";
        $data = $mysqli->query($query);
        $regionlist = array();
        if ($data->num_rows != 0)
        {
            //For each region
            while ($arr = $data->fetch_array(MYSQLI_ASSOC))
            {
                $regionid = $arr["RegionID"];
                $region = new Region($regionid);
                array_push($regionlist, $region);
            }
        }
        //If nothing is added (query failed, etc.) this will always return null
        return $regionlist;
    }
}

$factory = new Factory();

?>